package utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @version V1.0
 * @Title:
 * @Package
 * @Description:
 * @author: runoob
 * @date:
 */

public class AESUtils {

    public String dataSecret = "SqCOnJh7uGeAMlbx";
    public String dataSecretIV = "11nzh7uGeAMlbxJh";

    //加密
    /* str 源字符串
     * key 秘钥
     * iv 向量秘钥
     */

    public String Encrypt(String str) {
        String resultObj = null;
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKey secretKey = new SecretKeySpec(dataSecret.getBytes(StandardCharsets.UTF_8), "AES");
            //使用加密模式初始化 密钥
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(dataSecretIV.getBytes(StandardCharsets.UTF_8)));
            //按单部分操作加密或解密数据，或者结束一个多部分操作。
            byte[] encode = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
            resultObj = new BASE64Encoder().encode(encode);
        } catch (Exception ignored) {

        }
        return resultObj;
    }

    // 解密
    /* sSrc 源字符串
     * sKey 秘钥
     * ivStr 向量秘钥
     */
    public String Decrypt(String sSrc) {
        try {
            // 判断Key是否正确
            if (dataSecret == null) {
//                logger.error("AES解密的key为空");
                return null;
            }
            // 判断Key是否为16位
            if (dataSecret.length() != 16) {
//                logger.error("AES解密的key长度不是16位");
                return null;
            }
            byte[] raw = dataSecret.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(dataSecretIV.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                // originalString= unEscapeChar(originalString);
                return new String(original, StandardCharsets.UTF_8);
            } catch (Exception e) {
//                logger.error("base64解密错误", e);
                return null;
            }
        } catch (Exception ex) {
//            logger.error("AES解密错误", ex);
            return null;
        }
    }
}